package com.java.demo;

import com.java.oop.Student;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCDemo {

    private static final String url = "jdbc:mysql://localhost:3306/testdb?serverTimezone=GMT";

    public static int executeUpdate(String sql,Object... params){
        try( Connection conn = DriverManager.getConnection(url, "root", "123456") ){
            PreparedStatement ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1,params[i]);
            }
            int rs = ps.executeUpdate();
            return rs;
        }catch (SQLException ex){
            ex.printStackTrace();
        }
        return 0;
    }

    public static <T> List<T> executeQuery(Class clazz,String sql,Object... params){
        try( Connection conn = DriverManager.getConnection(url, "root", "123456") ){
            PreparedStatement ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1,params[i]);
            }
            ResultSet rs = ps.executeQuery();
            List<T> list = new ArrayList<>();
            while(rs.next()){
                Field[] fields = clazz.getDeclaredFields();
                Object object = clazz.newInstance();
                for(Field field : fields){
                    Object value = rs.getObject(field.getName());
                    field.setAccessible(true);
                    field.set(object,value);
                }
                list.add((T)object);
            }
            return list;
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws SQLException {
//        executeUpdate("insert into student(name,age,gender,address) values(?,?,?,?)",
//                "张章",22,"男","兰州");

        List<Student> students = executeQuery(Student.class, "select * from student");

        System.out.println(students);
    }
}
